package cn.jiyun.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    //前置拦截 到达controller之前处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("LoginInterceptor的preHandle执行了");
        //获取登录用户信息
        String user = (String) request.getSession().getAttribute("user");
        if(StringUtils.isNotBlank(user)){
            //用户登录了，直接放行请求
            return true;
        }
        //拦截请求
        return false;
    }

    //后置拦截 controller处理完毕后执行拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor的postHandle执行了");
    }

    //最终拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("LoginInterceptor的afterCompletion执行了");
    }
}
